import { create } from 'zustand';
import { devtools } from 'zustand/middleware';

export interface UserInfoState {
  userInfo: {
    id: string; // 用户id
    username: string; // 用户名
    phone: string; // 手机号
    password: string; // 密码
    avatar: string; // 头像
    bio: string; // 简介
    courses: number; // 课程数量
    likes: number; // 点赞数量
    createdAt: string; // 创建时间
  };
  token: string; // 令牌
}


interface UserInfoActions {
  setUserInfo: (userInfo: any) => void;
  setToken: (token: string) => void;
}

const useUserInfoStore = create(devtools<UserInfoState & UserInfoActions>((set) => ({
  userInfo: localStorage.getItem('userInfo') ? JSON.parse(localStorage.getItem('userInfo') || '{}') : {} as any,
  token: localStorage.getItem('toekn') || '',
  setUserInfo: (userInfo: any) => {
    set({ userInfo });
    if (Object.keys(userInfo).length > 0) {
      localStorage.setItem('userInfo', JSON.stringify(userInfo));
    } else {
      localStorage.removeItem('userInfo');
    }
  },
  setToken: (token: string) => {
    set({ token });
    if (token.length > 0) {
      localStorage.setItem('toekn', token);
    } else {
      localStorage.removeItem('toekn');
    }
  },
})));

export default useUserInfoStore;
